package config

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"strings"

	"gopkg.in/yaml.v3"
)

func LoadConfig(filename string) (map[string]string, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	kv := make(map[string]string)

	switch {
	case strings.HasSuffix(filename, ".yaml"), strings.HasSuffix(filename, ".yml"):
		var m map[string]interface{}
		if err := yaml.Unmarshal(data, &m); err != nil {
			return nil, err
		}
		flatten("", m, kv)
	case strings.HasSuffix(filename, ".json"):
		var m map[string]interface{}
		if err := json.Unmarshal(data, &m); err != nil {
			return nil, err
		}
		flatten("", m, kv)
	default:
		return nil, fmt.Errorf("不支持的配置文件格式")
	}

	return kv, nil
}

// 支持嵌套与数组 JSON 扁平化
func flatten(prefix string, in map[string]interface{}, out map[string]string) {
	for k, v := range in {
		fullKey := k
		if prefix != "" {
			fullKey = prefix + "." + k
		}
		switch val := v.(type) {
		case map[string]interface{}:
			flatten(fullKey, val, out)
		case []interface{}:
			if b, err := json.Marshal(val); err == nil {
				out[fullKey] = string(b) // 存JSON字符串
			}
		default:
			out[fullKey] = fmt.Sprintf("%v", val)
		}
	}
}
